<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2021/8/4
 * Time: 16:01
 */

namespace app\api\controller;


use think\Db;

class Apilogin extends Base
{
    /**
     * 发送验证码
     * @return \think\response\Json|void
     * phone       填写的手机号
     * type        发送场景   1 绑定手机号   2 手机号登录+验证码登录
     */
    public function getPhoneCode()
    {
        $params = input('');
        
        if(trim($params['phone'], ' ') == '') {
            return json(['status' => 0, 'msg' => '请输入手机号']);
        }
        if(!preg_match("/^1[3456789]\d{9}$/", $params['phone'])) {
            return json(['status'=>100,'msg'=>'请填写正确的手机号码']);
        }
        $userInfo = Db::table('up_u_user')->where('user_phone', $params['phone'])->find();
        if($userInfo && isset($params['type']) && $params['type'] == 1){
            return json(['status' => 0, 'msg' => '该手机号已被绑定']);
        }
        if(empty($userInfo) && isset($params['type']) && $params['type'] == 2) { // 手机号+验证码登录
            return json(['status' => 0, 'msg' => '该手机号未注册']);
        }
    
//        $code = GetRandCode(); // 6位数验证码
        $code = 111111;
    
//        $sendres = YzxSms($code, $params['phone'], '');//发送验证码
        $sendres = [
            'code' => 0
        ];
        if($sendres['code'] != 0) { // 发送不成功
            return json(['status' => 0, 'msg' => $sendres['msg']]);
        } else {
            $data = [
                'phone' => $params['phone'], // 发送的手机号
                'code' => $code, // 验证码
                'time' => time(), // 验证码发送的时间戳
                'date_time' => date('Y-m-d H:i:s') // 日期格式
            ];
            $res = Db::table('up_phonecode')->insert($data);
            if(!$res) {
                return json(['status' => 0, 'msg' => '数据库操作失败']);
            }
            return json(['status' => 200, 'msg' => $code]);
        }
    }
    
    /**
     * 微信授权
     */
    public function wxAuthor(){
        $code = input('code');
        $today = date('Y-m-d H:i:s');
        $open_id = $this->getOpenId($code);
        if($open_id){
            $user = Db::table('up_u_user')->where('user_wx_openid', $open_id)->find();
            if($user){
                return json(['status' => 200, 'msg' => $user]);
            }else{
                $data = [
                    'user_token' => md5(time()),
                    'user_time' => $today,
                    'user_update_time' => $today,
                    'user_wx_openid' => $open_id,
                ];
                Db::table('up_u_user')->insert($data);
                $user = Db::table('up_u_user')->where('user_wx_openid', $open_id)->find();
                return json(['status' => 200, 'msg' => $user]);
            }
        }else{
            return json(['status' => 100, 'msg' => '数据获取失败']);
        }
    }
    
    /**
     * 手机号登录
     * @return \think\response\Json
     * phone     手机号
     * code      验证码
     */
    public function phoneLogin(){
        $phone = trim(input('phone'));
        $code = trim(input('code'));
        
        if(!$phone) return json(['status' => 0, 'msg' => '请输入手机号']);
        if(!$code) return json(['status' => 0, 'msg' => '请输入验证码']);
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)) {
            return json(['status' => 0, 'msg' => '请输入正确格式的手机号']);
        }
        
        $user = Db::table('up_u_user')->where('user_phone', $phone)->find();
        if(!$user) return json(['status' => 0, 'msg' => '该手机号尚未注册']);
        if($user['user_status'] == 2) return json(['status' => 0, 'msg' => '该用户已被冻结']);
        if($user['user_status'] == 3) return json(['status' => 0, 'msg' => '账号异常，请联系管理员']);
    
        //=========验证验证码
        $res = Db::table('up_phonecode')
            ->where('phone', $phone)
            ->order('time desc')
            ->limit(1)
            ->find();
        if($code != $res['code']) {
            return json(['status' => 0, 'msg' => '验证码错误']);
        }
        // 10分钟超时
        $now = time();
        if($now - $res['time'] >= 601) {
            return json(['status' => 0, 'msg' => '验证码超时']);
        }
        if($res['status'] == 1) {
            return json(['status' => 0, 'msg' => '验证码已使用']);
        }
    
        $token = md5(date('YmdHis') . rand(100000, 999999));
        $result = Db::table('up_u_user')->where('user_phone', $phone)->update(['user_token' => $token]);
        if($result){
            //修改验证码状态
            Db::table('up_phonecode')->where('id', $res['id'])->setField('status', 1);
            $userInfo = Db::table('up_u_user')->where('user_phone', $phone)->find();
            return json(['status' => 200, 'msg' => $userInfo]);
        }else{
            return json(['status' => 0, 'msg' => '登录失败']);
        }
    }
    
    /**
     * 绑定手机号
     * @return \think\response\Json
     * phone      手机号
     * code       验证码
     */
    public function bandingPhone(){
        $phone = trim(input('phone'));
        $code = trim(input('code'));
        $user_id = trim(input('user_id'));

        if(!$phone) return json(['status' => 0, 'msg' => '请输入手机号']);
        if(!$code) return json(['status' => 0, 'msg' => '请输入验证码']);
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)) {
            return json(['status' => 0, 'msg' => '请输入正确格式的手机号']);
        }
        
        $user = Db::table('up_u_user')->where('user_phone', $phone)->find();
        if($user){
            return json(['status' => 0, 'msg' => '该手机号已绑定其它账号']);
        }
    
        //=========验证验证码
        $res = Db::table('up_phonecode')
            ->where('phone', $phone)
            ->order('time desc')
            ->limit(1)
            ->find();
        if($code != $res['code']) {
            return json(['status' => 0, 'msg' => '验证码错误']);
        }
        // 10分钟超时
        $now = time();
        if($now - $res['time'] >= 601) {
            return json(['status' => 0, 'msg' => '验证码超时']);
        }
        if($res['status'] == 1) {
            return json(['status' => 0, 'msg' => '验证码已使用']);
        }
        
        $result = Db::table('up_u_user')->where('user_id',$user_id)->update(['user_phone' => $phone]);
        if($result){
            //修改验证码状态
            Db::table('up_phonecode')->where('id', $res['id'])->setField('status', 1);
            $userInfo = Db::table('up_u_user')->where('user_phone', $phone)->find();
            return json(['status' => 200, 'msg' => $userInfo]);
        }else{
            return json(['status' => 0, 'msg' => '系统异常，绑定失败']);
        }
        
    }
    
    /**
     * 协议
     * @return \think\response\Json
     * type     3 平台用户协议   4 隐私协议
     */
    public function agreement(){
        $type = input('type'); // 3 用户协议   4 隐私协议
        $agreement = Db::table('up_about')
            ->where('about_id', $type)
            ->field('about_content content')
            ->find();
        return json(['status' => 200, 'msg' => $agreement]);
    }
    /**
     * 上传
     * 上传名字：image
     */
    public function uploadFile()
    {
        return json(['status'=>200,'msg'=>"https://jintianjifen.oss-cn-shanghai.aliyuncs.com/1577172495293"]);
//        $filePath = $_FILES['image']['tmp_name'];
//        $size = $_FILES['image']['size'];
//        if($size > 1024*1024*5){
//            return json(['status'=>100,'msg'=>"图片不得超过5M"]);
//        }
//        $type = explode(".",$_FILES['image']['name']);
//        $type = end($type);
//        $key = md5(time().uuid()).'.'.$type;
//        $up = new ossDemo();
//        $data = $up->uploadFile($filePath,$key);
//        return json(['status'=>200,'msg'=>"https://jintianjifen.oss-cn-shanghai.aliyuncs.com/{$data}"]);
    }
}